'use strict'

const Service = require('egg').Service
const jwt = require('jsonwebtoken')

class MysqlService extends Service {
  async login(userInfo) {
    let result = await this.app.mysql.query(
      'select * from chat_user where username=? and password=?',
      [userInfo.username, userInfo.password]
    )
    if (result.length > 0) {
      try {
        const token = await new Promise((resolve, reject) => {
          jwt.sign(
            {
              userid: result[0].id,
              username: result[0].username,
            },
            this.app.config.passportJwt.secret,
            {
              // token 有效时间 秒
              expiresIn: 3600,
            },
            (err, token) => {
              if (err) {
                reject(err)
              }
              resolve(token)
            }
          )
        })
        return {
          code: 0,
          message: '登录成功',
          token: 'Bearer ' + token,
        }
      } catch (err) {
        return {
          code: 1,
          message: '登录失败',
        }
      }
    } else {
      return {
        code: 1,
        message: '登录失败',
      }
    }
  }
  async getChatUserList() {
    let resultRes = await this.app.mysql.query('select * from c_router')

    function treeData(source, id, parentId, children) {
      let cloneData = JSON.parse(JSON.stringify(source))
      return cloneData.filter((father) => {
        let branchArr = cloneData.filter(
          (child) => father[id] == child[parentId]
        )
        branchArr.length > 0 ? (father[children] = branchArr) : ''
        return father[parentId] == 0 // 如果第一层不是parentId=0，请自行修改
      })
    }

    let result = treeData(resultRes, 'id', 'parent_id', 'children')

    function filterRouter(routers) {
      // 遍历后台传来的路由字符串，转换为组件对象
      const accessedRouters = routers.filter((route) => {
        // if (route.component) {
        //   if (route.component === 'Home') {
        //     // Home组件特殊处理
        //     route.component = Home
        //   } else {
        //     route.component = _import(route.component)
        //   }
        // }

        // console.log(route)
        // 拼接路由表
        route.meta = {
          title: route.title,
          icon: route.icon,
        }
        route.path = route.path
        route.component = '@/views' + route.component

        if (route.children && route.children.length) {
          route.alwayShow = true
          route.children = filterRouter(route.children)
        }

        // 删除不必要的属性
        delete route.id
        delete route.parent_id
        delete route.title
        delete route.icon

        return true
      })
      return accessedRouters
    }

    result = filterRouter(result)

    return {
      code: 0,
      message: '获取成功',
      result,
      payload: this.ctx.payload,
    }
  }
}

module.exports = MysqlService
